<template>
  <div class="corporation-container">
    <!-- 1 阐述声明 -->
    <div v-if="show_expound" class="expound">
      <div class="expound-title">请验证您的企业信息, 否则无法正常使用</div>
      <div class="expound-content">
        <div class="expount-content-item item-1">验证企业需要准备一下材料,准备好后开始填写.</div>
        <div class="expount-content-item item-2">
          1、资质证明文件。
          <br/>
          工商营业执照文件的电子照片或扫描。
          <br/>
          企业工商营业执照，<span class="license">需加盖与主体一致的单位公章。</span>
        </div>
        <div class="expount-content-item item-3">
          2、其他证明材料。
          <br/>
          如企业工商变更证明、官方红头文件、加盖公章证明等。
        </div>
      </div>
      <div class="expound-footer">
        <el-button class="fill-btn" @click="show_expound=false">我知道了,现在去验证</el-button>
        <el-button class="plain-btn" @click="backLogin">先不验证,退出</el-button>
      </div>
    </div>
    <!-- 2 详细填写内容 -->
    <el-form v-else ref="corpForm" :model="corpForm" :rules="rules" class="corpration-info" label-position="left">
      <!-- (1)企业资质 -->
      <div class="qualification">
        <el-row class="qualification-item" :gutter="20" type="flex" align="middle">
          <el-col :span="4">企业资质信息</el-col>
        </el-row>
        <el-row class="qualification-item" :gutter="20" type="flex" align="middle">
          <el-col :span="2">企业全称</el-col>
          <el-col :span="10">
            <el-form-item prop="companyName">
              <el-input ref="companyName" key="companyName" v-model="corpForm.companyName" placeholder="企业全称"
                name="companyName" type="text" tabindex="1" />
            </el-form-item>
          </el-col>
          <el-col :span="2">所属公司</el-col>
          <el-col :span="10">
            <el-form-item>
              <el-select v-model="corpForm.groupId" placeholder="所属公司" style="width: 100%;" ref="group_info">
                <el-option v-for="item in list_group" :key="item.id" :label="item.label" :value="item.id"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row class="qualification-item" :gutter="20" type="flex" align="middle">
          <el-col :span="10" :push="2">
            主体名称需严格按照证件填写,在注册确认后不可更改。
          </el-col>
          <el-col :span="2" :push="2">所属网点</el-col>
          <el-col :span="10" :push="2">
            <el-form-item>
              <addr-branch :select_level='1' :group_id="corpForm.groupId"  @changenode="handleAddr"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row class="qualification-item" :gutter="20" type="flex" align="middle">
          <el-col :span="2">营业执照</el-col>
          <el-col :span="20">请上传最新的营业执照,<span class="license">证件需要与主体一致的单位公章、无公章的个体工商户可加盖法人私章或法人签字。</span></el-col>
        </el-row>

        <el-row class="qualification-item" :gutter="20" type="flex" align="middle">
          <el-col :span="20" :push="2">
            加盖公章的扫描件或者复印件，支持 .jpg.jpeg.bmp.gif.png 格式的照片，大小不超过10M。
          </el-col>
        </el-row>

        <el-row class="qualification-item" :gutter="20" type="flex" align="middle">
          <!-- <el-col :span="5" :push="2">
            <div class="upload">点击上传图片</div>
          </el-col> -->
          <el-col :span="13" :push="2" >
            <!-- 营业执照 -->
            <div class="upload-container">
              <el-upload action="/api/kd-server/picture/upload" :file-list="license_list"
                  name="img" :headers=" { 'enctype': 'multipart/form-data',method: 'post'}" :data="{type: 'license_front'}"
                  :before-upload="licenseBeforeUpload" :on-success="licenseSuccess" multiple :limit="3" :show-file-list="false"
                  :on-exceed='licenseExceed'>
                <div class="upload-btn">营业执照正面</div>
              </el-upload>
              <div class="upload-img">
                <el-image class="avatar" v-for="(itemurl,i) in license_list2" :key="i" :src="itemurl" :preview-src-list="license_list2" fit="cover"></el-image>
              </div>
            </div>
          </el-col>
        </el-row>

        <el-row class="qualification-item" :gutter="20" type="flex" align="middle">
          <el-col :span="2">信用代码</el-col>
          <el-col :span="10">
            <el-form-item prop="unifiedSocialCreditCode">
              <el-input ref="unifiedSocialCreditCode" key="unifiedSocialCreditCode" v-model="corpForm.unifiedSocialCreditCode" placeholder="统一社会信用代码"
                name="unifiedSocialCreditCode" type="text" tabindex="2" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row class="qualification-item" :gutter="20" type="flex" align="middle">
          <el-col :span="10" :push="2">
            务必与营业执照上的注册号或统一社会信用代码一致。
          </el-col>
        </el-row>

        <el-row class="qualification-item" :gutter="20" type="flex" align="middle">
          <el-col :span="2">其他证明 材料 (选填)</el-col>
          <el-col :span="20">
            特殊情况可上传作为佐证,如企业工商变更证明、官方红头文件、加盖公章证明等。其他证明材料可上传最多10张
          </el-col>
        </el-row>

        <el-row class="qualification-item" :gutter="20" type="flex" align="middle">
          <el-col :span="20" :push="2">
            <!-- 其他材料 -->
            <div class="upload-container">
              <el-upload action="/api/kd-server/picture/upload" :file-list="doc_list"
                  name="img" :headers=" { 'enctype': 'multipart/form-data',method: 'post'}" :data="{type: 'credential'}"
                  :before-upload="docBeforeUpload" :on-success="docSuccess" multiple :limit="10" :show-file-list="false"
                  :on-exceed='docExceed'>
                <div class="upload-btn">点击上传图片</div>
              </el-upload>
              <div class="upload-img">
                <el-image class="avatar" v-for="(itemurl,i) in doc_list2" :key="i" :src="itemurl" :preview-src-list="doc_list2" fit="cover"></el-image>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
      <!-- (2)分隔线 -->
      <div class="separator"></div>
      <!-- (3)法人信息 -->
      <div class="legal">
        <el-row class="legal-item" :gutter="20" type="flex" align="middle">
          <el-col :span="4">企业资质信息</el-col>
        </el-row>
        <el-row class="legal-item" :gutter="20" type="flex" align="middle">
          <el-col :span="2">法人姓名</el-col>
          <el-col :span="10">
            <el-form-item prop="legalName">
              <el-input ref="legalName" key="legalName" v-model="corpForm.legalName" placeholder="法人姓名"
                name="legalName" type="text" tabindex="3" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="legal-item" :gutter="20" type="flex" align="middle">
          <el-col :span="2">身份证号</el-col>
          <el-col :span="10">
            <el-form-item prop="legalIdCode">
              <el-input ref="legalIdCode" key="legalIdCode" v-model="corpForm.legalIdCode" placeholder="法人身份证号码"
                name="legalIdCode" type="text" tabindex="4" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="legal-item" :gutter="20" type="flex" align="middle">
          <el-col :span="2">法人电话</el-col>
          <el-col :span="10">
            <el-form-item prop="legalTel">
              <el-input ref="legalTel" key="legalTel" v-model="corpForm.legalTel" placeholder="法人电话"
                name="legalTel" type="text" tabindex="5" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="legal-item" :gutter="20" type="flex" align="middle">
          <el-col :span="2">验证码</el-col>
          <el-col :span="10">
            <el-form-item prop="verify">
              <el-input key="verify" ref="verify" v-model="corpForm.verify" type="text" placeholder="短信验证码" name="verify" tabindex="6">
                <div class="verify-mess" :class="verify_css(verify_disable)" slot="append" @click="getVerifyMsg()">
                  {{ verify_btn }}
                </div>
              </el-input>
            </el-form-item>

          </el-col>
        </el-row>
      </div>
      <!-- (4)底部按钮 -->
      <div class="corporation-footer">
        <el-button class="fill-btn" @click="commitInfo">提交</el-button>
        <el-button class="plain-btn" @click="backLogin">取消</el-button>
      </div>
    </el-form>
  </div>
  
</template>

<script>
import { validMobile, validFixed, validSocialCredit, validIdCard } from '@/utils/validate'
import { checkApprove } from '@/api/permission'
import AddrBranch from '@/components/Address/AddrBranchSelect.vue'
import Qs from 'qs'

export default {
  name: 'Corporation',
  components: { AddrBranch },
  data() {
    const validateCorpphone = (rule, value, callback) => {
      if (!validMobile(value) && !validFixed(value)) {
        callback(new Error('电话号格式不正确!  例:151xxxxxxxx, 0779-xxxxxxxx'))
      } else { callback() }
    }
    const validatePhone = (rule, value, callback) => {
      if (!validMobile(value)) {
        callback(new Error('手机号格式不正确!'))
      } else { callback() }
    }
    const validateUscc = (rule, value, callback) => {
      if (!validSocialCredit(value)) {
        callback(new Error('统一社会信用码格式不正确!'))
      } else { callback() }
    }
    const validateName = (rule, value, callback) => {
      if (value.length < 1) {
        callback(new Error('不能为空!'))
      } 
      else { callback() }
    }
    const validateVerify = (rule, value, callback) => {
      if (value && value.length != 6) {
        callback(new Error('验证码为6位!'))
      } else { callback() }
    }
    const validateIdcard = (rule, value, callback) => {
      if (!validIdCard(value)) {
        callback(new Error('身份证格式不正确!'))
      } else { callback() }
    }

    const that = this
    return {
      show_expound: true,   // 是否显示声明页

      list_group: [{id:11, label: '邮政'},{id:12, label: '圆通'},{id:13, label: '申通'},{id:14, label: '中通'},{id:15, label: '韵达'},{id:16, label: '顺丰'}],
      corpForm: {
        companyName: '',   // 公司全称
        company: '邮政',   // 所属公司
        groupId: 11,   // 所属公司id
        address: '',   // 所属地区
        deptId: '',   // 所属网点
        unifiedSocialCreditCode: '',   // 统一信用代码
        legalName: '',   // 法人姓名
        legalIdCode: '',   // 法人身份证号
        legalTel: '',   // 法人电话
        verify: '',
        accpetStatus: 1,   // 审批状态
        uploadStatus: 1,   // 是否上传资料
      },
      rules: {
        companyName: [{ required: true, trigger: 'blur', validator: validateName }],
        unifiedSocialCreditCode: [{ required: true, trigger: 'blur', validator: validateUscc }],
        legalTel: [{ required: true, trigger: 'blur', validator: validatePhone }],
        legalName: [{ required: true, trigger: 'blur', validator: validateName }],
        legalIdCode: [{ required: true, trigger: 'blur', validator: validateIdcard }],
        verify: [{ required: true, trigger: 'blur', validator: validateVerify }],
      },
      verify_disable: '',
      verify_btn: '获取验证码',

      img_url: '',
      license_success: false, // 营业执照是否上传成功
      license_list: [],   // 营业执照列表
      license_list2: [],   // 营业执照列表--回显
      doc_success: false, // 证明材料是否上传成功
      doc_list: [],   // 其他资料列表
      doc_list2: [],   // 其他资料列表--回显
      down_time: 60, // 倒计时
      mark: '', // 用户的标识 56a2-1622119438192-5336
      corporation_loading: false,
    }
  },
  computed: {
    param_data() {
      if (this.corpForm.password && this.corpForm.phone) {
        const cryptograph = this.$sha256(this.corpForm.password + this.corpForm.phone)
        return { 'phone': this.corpForm.phone, 'password': cryptograph }
      } else { return {} }
    },
    verify_css() {
      return (dis) => {
        if (!dis) {
          return 'verifyactive'
        } 
        else { return 'verifydefault' }
      }
    },
  },
  watch: {
  },
  created() {
    // window.addEventListener('storage', this.afterQRScan)
    this.mark = this.$route.query.my_mark
    this.corpForm.phone = window.localStorage.getItem('phone' + this.mark)
    this.corpForm.password = window.localStorage.getItem('password' + this.mark)
  },
  mounted() {
    // if (this.corpForm.userphone === '') {
    //   this.$refs.userphone.focus()
    // } else if (this.corpForm.password === '') {
    //   this.$refs.password.focus()
    // }
  },
  destroyed() {
    // window.removeEventListener('storage', this.afterQRScan)
  },
  methods: {
    // 返回登录页
    backLogin() {
      this.show_expound = true
      this.$router.replace({ path: '/login'})
    },
    // 选择网点
    handleAddr(code, level, newval) {
      this.corpForm.deptId = code
    },


    // 上传营业执照: 前置钩子
    licenseBeforeUpload(file) {
      const isJPG = (file.type === 'image/jpeg' || file.type === 'image/png')
      const isLt10M = file.size / 1024 / 1024 < 10

      if (!isJPG) {
        this.$message.error('营业执照图片只能是 JPG/JPEG/PNG!')
      }
      if (!isLt10M) {
        this.$message.error('营业执照图片大小不能超过 10MB!')
      }
      return isJPG && isLt10M
    },
    // 营业执照上传成功
    licenseSuccess(res, file, filelist) {
      this.license_list2 = filelist.map((item, i) => {
        return URL.createObjectURL(item.raw)   //  转成url ###
      })
      if (res.code == 0) {
        console.log(res);
        this.license_success = true
      }
    },
    // 上传营业执照超出上限
    licenseExceed(files, fileList) {
      this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },

    // 上传其他材料: 前置钩子
    docBeforeUpload(file) {
      const isJPG = (file.type === 'image/jpeg' || file.type === 'image/png')
      const isLt10M = file.size / 1024 / 1024 < 10

      if (!isJPG) {
        this.$message.error('其他材料图片只能是 JPG/JPEG/PNG!')
      }
      if (!isLt10M) {
        this.$message.error('其他材料图片大小不能超过 10MB!')
      }
      return isJPG && isLt10M
    },
    // 其他材料上传成功
    docSuccess(res, file, filelist) {
      this.doc_list2 = filelist.map((item, i) => {
        return URL.createObjectURL(item.raw)   //  转成url ###
      })
      if (res.code == 0) {
        this.doc_success = true
      }
    },
    // 上传其他材料超出上限
    docExceed(files, fileList) {
      this.$message.warning(`当前限制选择 10 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },


    // 获取验证码 和 倒计时
    getVerifyMsg() {
      let interval
      if (!validMobile(this.corpForm.legalTel)) {
        this.$message({
          message: '号码格式不正确',
          type: 'error',
          duration: 4000,
        })
        this.verify_btn = '获取验证码'
        this.verify_disable = false
        this.down_time = 60
        window.clearInterval(interval)
        // callback(new Error('格式不正确!'))
      }
      else {
        const that = this

        interval = window.setInterval(() => {
          that.verify_btn = '重新获取(' + that.down_time + '秒)'
          --that.down_time
          if (that.down_time < 0) {
            that.verify_btn = '获取验证码'
            this.verify_disable = false
            that.down_time = 60
            window.clearInterval(interval)
          }
        }, 1000)

        // 网络请求: 获取手机验证码

      }
      
    },

    // 提交企业信息=======================================================================================
    commitInfo() {
      this.list_group.forEach((item,i) => {
        if(item.id == this.groupId) {this.company = item.label}
      })
      this.corpForm.address = ` ${window.localStorage.getItem('corporation_prin')}-${window.localStorage.getItem('corporation_city')}-${window.localStorage.getItem('corporation_area')}-${window.localStorage.getItem('corporation_street')} `
      console.log(this.corpForm.address);

      this.$refs.corpForm.validate(valid => {
        if(valid) {
          if (!this.license_success) {
            this.$message({
              message: '请上传营业执照!',
              type: 'error',
              duration: 4000,
              showClose: true,
              center: true
            })
          }
          else if(this.corpForm.groupId == '') {
            this.$message({
              message: '请选择所属公司!',
              type: 'error',
              duration: 4000,
              showClose: true,
              center: true
            })
          }
          else if(this.corpForm.deptId == '') {
            this.$message({
              message: '请选择所属网点!',
              type: 'error',
              duration: 4000,
              showClose: true,
              center: true
            })
          }
          else {
            this.reg_loading = true
            // 发送提交企业信息的 网络请求,
            checkApprove(this.corpForm).then(res => {
              if (res.code == 0) {
                this.$message({
                  message: '提交成功!',
                  type: 'success',
                  duration: 4000,
                  showClose: true,
                  center: true
                })
                // 成功之后
                this.reg_loading = false
                this.$router.replace('/login')
              }
              else {
                this.$message({
                  message: '提交失败!',
                  type: 'error',
                  duration: 4000,
                  showClose: true,
                  center: true
                })
              }
            }).catch(() => {
              this.reg_loading = false
            })
          }
        }
        else { return false}
      })
      
      
    },

  }
}
</script>

<style lang="scss">
$border_color: #D4D4D4;
$border_light: #D9DADA;
$theme: #00805a;
$theme_bg: #2b303b;
$text_light: #9fa1a2;
$text_middle: #c0c0c0;
$obj_white: #ffffff;

.corporation-container {
  .el-form{
    .el-form-item {
      margin-bottom: 0 !important;
    }
  }
}

.plain-btn {
  color: $theme;
  &.el-button--medium {
    font-size: 12px;
    padding: 0 10px;
    border-radius: 3px !important;
  }
  &.el-button {
    height: 27px;
    border: 1px solid $theme !important;
  }
}
.fill-btn {
  color: #fff;
  &.el-button--medium {
    font-size: 12px;
    padding: 0 10px;
    border-radius: 3px !important;
  }
  &.el-button {
    height: 27px;
    background-color: $theme;
  }
}

</style>

<style lang="scss" scoped>
$bg:rgba(0,0,0,0);
$cursor: #5E5E5E;

$bgc: #fff;
$dark_text: #5E5E5E;
$light_text: #B3B3B3;
$theme_color: rgba(15, 139, 253, 1);
$theme_color_light: rgba(15, 139, 253, 0.5);
$text_color: #fff;

$border_color: #D4D4D4;
$border_light: #D9DADA;
$theme: #00805a;
$theme_bg: #2b303b;
$text_light: #9fa1a2;
$text_middle: #c0c0c0;
$obj_white: #ffffff;
$remove_red: #ff4c4c;

.corporation-container {
  width: 100%;
  height: 100%;
  min-width: 1300px;
  min-height: 680px;
  overglow: hidden;
  background-color: #878787;
  opacity: 0.75;
  display: flex;
  align-items: center;
  justify-content: center;
  // 1企业信息 提示页
  .expound {
    width: 960px;
    height: 520px;
    background: $bgc;
    border-radius: 2px;
    position: relative;
    padding: 25px 50px;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    align-items: center;
    font-size: 14px;
    .expound-title {
      font-size: 25px;
    }
    .expound-content {
      .item-1,.item-2 { 
        margin-bottom: 25px;
      }
      .item-2 {
        .license {
          color: $remove_red;
        }
      }
    }
    .expound-footer {
      
    }
  }
  // 2企业信息详情
  .corpration-info {
    width: 1200px;
    height: 620px;
    background-color: $bgc;
    border-radius: 3px;
    position: relative;
    padding: 33px;
    overflow: scroll;
    font-size: 14px;
    .qualification {
      // background-color: #eef;
      .qualification-item {
        margin-bottom: 20px;
        .upload-container {   // 营业执照图片 上传区域
        background-color: #def;
          // height: 100px;
          display: flex;  
          .upload-btn {
            width: 100px;
            height: 30px;
            line-height: 30px;
            text-align: center;
            border: 1px solid $border_color;
            border-radius: 3px;
            font-size: 12px;
            cursor: pointer;
            margin-right: 20px;
          }
          .upload-img {
            background-color: #ffe;
            flex: 1;
            .avatar {
              width: 100px;
              height: 100px;
              margin-right: 10px;
            }
          }
        }
        
        .license {
          color: $remove_red;
        }
      }
    }

    .separator {
      height: 1px;
      background-color: $border_color;
      margin: 20px 0;
    }
    .legal {
      .legal-item {
        margin-bottom: 20px;
        .verify-mess {
          cursor: pointer;
          font-size: 12px;
        }
      }
    }
    .corporation-footer{
      width: 100%;
      display: flex;
      justify-content: center;
    }
  }


}

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

  @media only screen and (max-width: 470px) {
    .thirdparty-button {
      display: none;
    }
  }
</style>
